<template>
  <ContentWrap>
    <Search :schema="searchSchema" title-width="68px">
      <template #actionMore>
        <el-button type="success" plain @click="loadData">
          <Icon icon="ep:refresh" /> 刷新
        </el-button>
      </template>
    </Search>
  </ContentWrap>

  <ContentWrap>
    <TableV2
      :data="tableData"
      :columns="tableColumns"
      :loading="loading"
      height="52vh"
      :table-set-props="{
        fixed: true,
        rowKey: 'id',
        rowHeight: 44
      }"
    />
  </ContentWrap>
</template>

<script lang="tsx" setup>
import { ref, withKeys, unref } from 'vue'
import { ElCheckbox } from 'element-plus'
import { CheckboxValueType } from 'element-plus'
import { ElInput } from 'element-plus'
import { ElTimePicker } from 'element-plus'
//import { DictTag } from '@/components/DictTag'
//import { DICT_TYPE } from '@/utils/dict'

const searchSchema = ref<any[]>([
  {
    key: 'recordDate',
    title: '配餐日期',
    component: 'DatePicker',
    componentProps: { placeholder: '选择日期', valueFormat: 'YYYY-MM-DD', type: 'date' }
  },
  {
    key: 'depTime',
    title: '起飞时间',
    component: 'TimePicker',
    componentProps: { placeholder: '起飞时间', format: 'HH:mm', valueFormat: 'HH:mm' }
  },
  {
    key: 'airlinePattern',
    title: '机型',
    component: 'Select',
    componentProps: { placeholder: '机型', clearable: true, options: [] }
  },
  {
    key: 'flightNo',
    title: '航班号',
    component: 'Input',
    componentProps: { placeholder: '航班号', clearable: true }
  }
])

// Reuse InputCell / TimerPickerCell patterns from index.vue
const InputCell = ({ value, onChange, onBlur, onKeydownEnter, forwardRef, key }) => (
  <ElInput
    ref={forwardRef as any}
    key={key}
    onInput={onChange}
    onBlur={onBlur}
    onKeydown={withKeys(onKeydownEnter, ['enter'])}
    modelValue={value}
  />
)

const InputCellRender = ({ rowData, column }) => {
  const editKey = '_' + column.dataKey
  const onChange = (value: string) => (rowData[column.dataKey!] = value)
  const onEnterEditMode = () => (rowData[editKey] = true)
  const onExitEditMode = () => (rowData[editKey] = false)
  const input = ref()
  const setRef = (el) => {
    input.value = el
    if (el) el.focus?.()
  }
  return rowData[editKey] ? (
    <InputCell
      key="write"
      forwardRef={setRef}
      value={rowData[column.dataKey!]}
      onChange={onChange}
      onBlur={onExitEditMode}
      onKeydownEnter={onExitEditMode}
    />
  ) : (
    <ElInput
      key="readonly"
      modelValue={rowData[column.dataKey]}
      readonly={true}
      onClick={onEnterEditMode}
    ></ElInput>
  )
}

const TimerPickerCell = ({ value, handleChange, onBlur, forwardRef }) => (
  <ElTimePicker
    ref={forwardRef}
    modelValue={value}
    onChange={handleChange}
    onUpdate:modelValue={handleChange}
    onBlur={onBlur}
    format="HH:mm"
    value-format="HH:mm"
    editable
  />
)

const TimerPickerCellRender = ({ rowData, column }) => {
  const editKey = '_' + column.dataKey
  const onChange = (value: string) => {
    rowData[column.dataKey!] = value
    column.editing = false
  }
  const onEnterEditMode = () => (rowData[editKey] = true)
  const onExitEditMode = () => (rowData[editKey] = false)
  const pickerRef = ref()
  const setRef = (el) => {
    pickerRef.value = el
    if (el) {
      el.focus?.()
      el.handleOpen?.()
    }
  }
  return rowData[editKey] ? (
    <TimerPickerCell
      forwardRef={setRef}
      value={rowData[column.dataKey!]}
      handleChange={onChange}
      onBlur={onExitEditMode}
    />
  ) : (
    <ElInput modelValue={rowData[column.dataKey]} readonly onClick={onEnterEditMode}></ElInput>
  )
}

const tableColumns: any[] = [
  { type: 'index', title: '序号', width: 70 },
  {
    title: '起飞时间',
    key: 'depTime',
    dataKey: 'depTime',
    width: 120,
    cellRenderer: TimerPickerCellRender
  },
  { title: '机型', key: 'airlinePattern', dataKey: 'airlinePattern', width: 150 },
  { title: '配餐日期', key: 'recordDate', dataKey: 'recordDate', width: 110 },
  { title: '航线', key: 'route', dataKey: 'route', width: 150 },
  { title: '航班号', key: 'flightNo', dataKey: 'flightNo', width: 120 },
  { title: '舱位', key: 'cabin', dataKey: 'cabin', width: 70 },
  { title: '人数', key: 'people', dataKey: 'people', width: 90, cellRenderer: InputCellRender },
  { title: '数量', key: 'qty', dataKey: 'qty', width: 90, cellRenderer: InputCellRender },
  {
    title: '核查',
    key: 'check',
    dataKey: 'check',
    width: 80,
    cellRenderer: ({ rowData }) => (
      <ElCheckbox modelValue={rowData.check} onChange={(v) => (rowData.check = v)} />
    )
  },
  {
    title: '安化',
    key: 'safety',
    dataKey: 'safety',
    width: 80,
    cellRenderer: ({ rowData }) => (
      <ElCheckbox modelValue={rowData.safety} onChange={(v) => (rowData.safety = v)} />
    )
  }
]

// add selection column (like index.vue)
tableColumns.unshift({
  key: 'selection',
  width: 30,
  cellRenderer: ({ rowData }) => {
    const onChange = (value: CheckboxValueType) => (rowData.checked = value)
    return <ElCheckbox onChange={onChange} modelValue={rowData.checked} />
  },
  headerCellRenderer: ({}) => {
    const _data = unref(tableData)
    const onChange = (value: CheckboxValueType) =>
      (tableData.value = _data.map((r) => {
        r.checked = value
        return r
      }))
    const allSelected = _data.every((row) => row.checked)
    const containsChecked = _data.some((row) => row.checked)
    return (
      <ElCheckbox
        modelValue={allSelected}
        indeterminate={containsChecked && !allSelected}
        onChange={onChange}
      />
    )
  }
})

const loading = ref(false)
const tableData = ref([] as any[])

// Quick stub load
const loadData = async () => {
  loading.value = true
  tableData.value = Array.from({ length: 8 }).map((_, i) => ({
    id: i + 1,
    depTime: '06:3' + (i % 3),
    airlinePattern: i % 2 ? 'B737-7' : 'A321-7',
    recordDate: '2025-11-30',
    route: '深圳-广州',
    flightNo: 'DZ' + (6229 + i),
    cabin: 'Y',
    people: 0 + i * 10,
    qty: 0,
    checked: false,
    check: false,
    safety: false
  }))
  loading.value = false
}

loadData()
</script>

<style scoped lang="scss">
.table-actions {
  display: flex;
  gap: 8px;
}
</style>
